//
//  RegisterDetailViewController.m
//  EasyToo
//
//  Created by Jr Lan on 13-8-24.
//
//

#import "RegisterDetailViewController.h"
#import "LoginViewController.h"
#import "LeveyTabBarController.h"
#import <QuartzCore/QuartzCore.h>

@interface RegisterDetailViewController ()

@end

@implementation RegisterDetailViewController
{
    UIAlertView *_baseAlert;
    
    UIImageView *_imgview;
    UITextField *_nameTF;
    UITextField *_identifyTF;
    UILabel *_descLbl;
    UITextField *_passTF;
    UITextField *_repassTF;
    UIButton *_getprotocalBtn;
    UIButton *_registerBtn;
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    
    //初始化视图
    [self initScrollView];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


//实始化描述
- (void)initScrollView
{
    int width = [DeviceUtil getScreenWidth];
    int heigth = self.view.frame.size.height;
    
    UIScrollView *myscrollview = [[[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, width, heigth)]autorelease];
    myscrollview.directionalLockEnabled = YES; //只能一个方向滑动
    myscrollview.pagingEnabled = NO; //是否翻页
    myscrollview.backgroundColor = [UIColor whiteColor];
    myscrollview.showsVerticalScrollIndicator =YES; //垂直方向的滚动指示
    myscrollview.indicatorStyle = UIScrollViewIndicatorStyleWhite;//滚动指示的风格
    myscrollview.showsHorizontalScrollIndicator = NO;//水平方向的滚动指示
    myscrollview.delegate = self;
    CGSize newSize = CGSizeMake(width, 1000);
    [myscrollview setContentSize:newSize];
    
    UIControl *control = [[[UIControl alloc] initWithFrame:myscrollview.frame] autorelease];
    [myscrollview addSubview:control];
    [control addTarget:self action:@selector(onBackgroudTouch) forControlEvents:UIControlEventTouchDown];

    //头像显示
    _imgview = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"1.png"]];
    _imgview.frame = CGRectMake(120, 20, 80, 80);
    [myscrollview addSubview:_imgview];
    
    //姓名
    _nameTF = [[UITextField alloc] initWithFrame:CGRectMake(20, 110, 280, 50)];
    _nameTF.font = [UIFont fontWithName:@"Arial" size:18.0f];
    _nameTF.textColor = [UIColor blackColor];
    _nameTF.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    _nameTF.borderStyle = UITextBorderStyleRoundedRect;
    _nameTF.delegate = self ;
    _nameTF.returnKeyType =UIReturnKeyDone;
    _nameTF.layer.borderColor = [UIColor grayColor].CGColor;
    _nameTF.layer.borderWidth = 1 ;
    _nameTF.layer.cornerRadius = 10 ;
    _nameTF.keyboardType = UIKeyboardTypeNumberPad;
    _nameTF.placeholder = [NSString stringWithFormat:@"直接姓名"];
    _nameTF.text = self.mobile;
    _nameTF.clearsOnBeginEditing = YES;
    [myscrollview addSubview:_nameTF];
    
    //身份证号码
    _identifyTF = [[UITextField alloc] initWithFrame:CGRectMake(20, 170, 280, 50)];
    _identifyTF.text = @"";
    _identifyTF.placeholder = @"身份证号码";
    _identifyTF.keyboardType = UIKeyboardTypeNumberPad;
    _identifyTF.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    _identifyTF.borderStyle = UITextBorderStyleRoundedRect;
    _identifyTF.delegate = self ;
    _identifyTF.returnKeyType =UIReturnKeyDone;
    _identifyTF.layer.borderColor = [UIColor grayColor].CGColor;
    _identifyTF.layer.borderWidth = 1 ;
    _identifyTF.layer.cornerRadius = 10 ;
    [myscrollview addSubview:_identifyTF];
    
    //说明
    _descLbl = [[UILabel alloc]initWithFrame:CGRectMake(20, 230, 280, 20)];
    _descLbl.text = @"有效身份证号码是您彩票中奖后领取的唯一保证";
    _descLbl.font = [UIFont systemFontOfSize:20];
    _descLbl.adjustsFontSizeToFitWidth = YES;
    _descLbl.textColor = [UIColor grayColor];
    [myscrollview addSubview:_descLbl];
    
    //密码
    _passTF = [[UITextField alloc] initWithFrame:CGRectMake(20, 260, 280, 50)];
    _passTF.text = @"";
    _passTF.placeholder = @"设置登录密码（必填）";
    [_passTF setSecureTextEntry:YES];
    _passTF.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    _passTF.borderStyle = UITextBorderStyleRoundedRect;
    _passTF.delegate = self ;
    _passTF.returnKeyType =UIReturnKeyDone;
    _passTF.layer.borderColor = [UIColor grayColor].CGColor;
    _passTF.layer.borderWidth = 1 ;
    _passTF.layer.cornerRadius = 10 ;
    [myscrollview addSubview:_passTF];
    
    //重复密码
    _repassTF = [[UITextField alloc] initWithFrame:CGRectMake(20, 320, 280, 50)];
    _repassTF.text = @"";
    _repassTF.placeholder = @"再次设置登录密码（必填）";
    [_repassTF setSecureTextEntry:YES];
    _repassTF.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    _repassTF.borderStyle = UITextBorderStyleRoundedRect;
    _repassTF.delegate = self ;
    _repassTF.returnKeyType =UIReturnKeyDone;
    _repassTF.layer.borderColor = [UIColor grayColor].CGColor;
    _repassTF.layer.borderWidth = 1 ;
    _repassTF.layer.cornerRadius = 10 ;
    [myscrollview addSubview:_repassTF];
    
    //阅读注册协议
    _getprotocalBtn = [[UIButton alloc]initWithFrame:CGRectMake(190, 380, 150, 20)];
    [_getprotocalBtn setTitle:@"查看注册协议" forState:UIControlStateNormal];
    _getprotocalBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    [_getprotocalBtn setBackgroundColor:[UIColor clearColor]];
    [_getprotocalBtn setTitleColor:[UIColor grayColor]forState:UIControlStateNormal];
    [myscrollview addSubview:_getprotocalBtn];
    [_getprotocalBtn addTarget:self action:@selector(protocalEvent) forControlEvents:UIControlEventTouchUpInside];
    
    //注册
    _registerBtn = [[UIButton alloc]initWithFrame:CGRectMake(20, 410, 280, 40)];
    if (self.type == 1) {
        [_registerBtn setTitle:@"注册" forState:UIControlStateNormal];
    } else {
        [_registerBtn setTitle:@"重置密码" forState:UIControlStateNormal];
    }

    _registerBtn.titleLabel.font = [UIFont systemFontOfSize:12];
    [_registerBtn setBackgroundColor:[UIColor redColor]];
    [_registerBtn setTitleColor:[UIColor whiteColor]forState:UIControlStateNormal];
    _registerBtn.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    _registerBtn.layer.borderColor = [UIColor grayColor].CGColor;
    _registerBtn.layer.borderWidth = 1 ;
    _registerBtn.layer.cornerRadius = 10 ;
    [myscrollview addSubview:_registerBtn];
    [_registerBtn addTarget:self action:@selector(registerEvent) forControlEvents:UIControlEventTouchUpInside];
    
    [self.view addSubview:myscrollview];
}


//查看登录协议
- (void)protocalEvent
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"注册协议" message:@"同意注册" delegate:self cancelButtonTitle:@"同意" otherButtonTitles:@"不同意", nil];
    
    [alert show];
    
}

//注册
- (void)registerEvent
{
    if ([_nameTF.text isEqualToString:@""] == YES || [_identifyTF.text isEqualToString:@""] == YES) {
        _baseAlert = [[UIAlertView alloc]  initWithTitle:@"注册出错" message:@"请填写完整的注册信息"  delegate:self cancelButtonTitle:@"返回" otherButtonTitles: nil];
        [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(performDismiss:) userInfo:nil repeats:NO];
        [_baseAlert show];
    }
    
    //检测密码是否为空
    if ([_passTF.text isEqualToString:@""] == YES || [_repassTF.text isEqualToString:@""] == YES) {
        _baseAlert = [[UIAlertView alloc]  initWithTitle:@"注册出错" message:@"密码不能为空"  delegate:self cancelButtonTitle:@"返回" otherButtonTitles: nil];
        [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(performDismiss:) userInfo:nil repeats:NO];
        [_baseAlert show];
    }
    
    //检测密码是否一致
    if (![_passTF.text isEqualToString:_repassTF.text]) {
        _baseAlert = [[UIAlertView alloc]  initWithTitle:@"注册出错" message:@"两次密码不一致"  delegate:self cancelButtonTitle:@"返回" otherButtonTitles: nil];
        [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(performDismiss:) userInfo:nil repeats:NO];
        [_baseAlert show];
    }

    
    //成功注册
    else{
        //用户注册
        AccountManager *accountmanager = [AccountManager shareManager];
        accountmanager.delegate = self;
        if (self.type == 1) {
            //注册
            [accountmanager resetPasswd:self.mobile password:_passTF.text cardId:@"" apiCode:@"999014"];
            //[accountmanager userRegister:self.mobile password:_passTF.text cardId:_identifyTF.text];
        }
//        else {
//            //忘记密码
//            [accountmanager resetPasswd:self.mobile password:_passTF.text cardId:_identifyTF.text];
//        }
    }
}


- (void) performDismiss: (NSTimer *)timer {
    [_baseAlert dismissWithClickedButtonIndex:0 animated:NO];//important
    [_baseAlert release];
    _baseAlert = NULL;
}


//开始编辑输入框的时候，软键盘出现，执行此事件
-(void)textFieldDidBeginEditing:(UITextField *)textField
{
    CGRect frame = textField.frame;
    int offset = frame.origin.y + 32 - (self.view.frame.size.height - 216.0);//键盘高度216
    
    NSTimeInterval animationDuration = 0.30f;
    [UIView beginAnimations:@"ResizeForKeyboard" context:nil];
    [UIView setAnimationDuration:animationDuration];
    
    //将视图的Y坐标向上移动offset个单位，以使下面腾出地方用于软键盘的显示
    if(offset > 0)
        self.view.frame = CGRectMake(0.0f, -offset, self.view.frame.size.width, self.view.frame.size.height);
    
    [UIView commitAnimations];
}


//输入框编辑完成以后，将视图恢复到原始状态
-(void)textFieldDidEndEditing:(UITextField *)textField
{
    self.view.frame =CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
}


#pragma mark UITextFieldDelegate
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [_nameTF resignFirstResponder];
    [_identifyTF resignFirstResponder];
    [_passTF resignFirstResponder];
    [_repassTF resignFirstResponder];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}

- (void)onBackgroudTouch
{
    [_nameTF resignFirstResponder];
    [_identifyTF resignFirstResponder];
    [_passTF resignFirstResponder];
    [_repassTF resignFirstResponder];
}


//用户注册
- (void)registerUser:(BOOL)isSuccess accstatus:(NSString*)accstatus
{
    if (isSuccess) {
        NSUserDefaults *_userDefaults = [NSUserDefaults standardUserDefaults];
        [_userDefaults setBool:YES forKey:@"isLogin"];
        [_userDefaults setValue:self.mobile forKey:@"userName"];
        [_userDefaults setValue:_passTF.text forKey:@"passWord"];
        [_userDefaults synchronize];
        LoginViewController *loginViewController=[[LoginViewController alloc] init];
        [self.navigationController pushViewController:loginViewController animated:YES];
        [loginViewController release];
        //[self.leveyTabBarController setSelectedIndex:0];
    } else {
        _baseAlert = [[UIAlertView alloc]  initWithTitle:@"注册失败" message:@"请换个手机号试试，谢谢"  delegate:self cancelButtonTitle:@"返回" otherButtonTitles: nil];
        [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(performDismiss:) userInfo:nil repeats:NO];
        [_baseAlert show];
    }
    
}

//重置密码
- (void)resetPasswd:(BOOL)isSuccess
              point:(NSString*)point
{
    if (isSuccess) {
        NSUserDefaults *_userDefaults = [NSUserDefaults standardUserDefaults];
        [_userDefaults setBool:YES forKey:@"isLogin"];
        [_userDefaults setValue:self.mobile forKey:@"userName"];
        [_userDefaults setValue:_passTF.text forKey:@"passWord"];
        [_userDefaults synchronize];
        LoginViewController *loginViewController=[[LoginViewController alloc] init];
        [self.navigationController pushViewController:loginViewController animated:YES];
        [loginViewController release];
        //[self.leveyTabBarController setSelectedIndex:0];
    } else {
        _baseAlert = [[UIAlertView alloc]  initWithTitle:@"注册失败" message:@"请换个手机号试试，谢谢"  delegate:self cancelButtonTitle:@"返回" otherButtonTitles: nil];
        [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(performDismiss:) userInfo:nil repeats:NO];
        [_baseAlert show];
    }
//    if (isSuccess) {
//        LoginViewController *loginViewController=[[LoginViewController alloc] init];
//        [self.navigationController pushViewController:loginViewController animated:YES];
//        [loginViewController release];
//    } else {
//        _baseAlert = [[UIAlertView alloc]  initWithTitle:@"重置密码失败" message:@"请重新提交试试，谢谢"  delegate:self cancelButtonTitle:@"返回" otherButtonTitles: nil];
//        [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(performDismiss:) userInfo:nil repeats:NO];
//        [_baseAlert show];
//    }
}

@end
